package spm.project.rememberme;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class SingleGame extends Activity {
	int row, column;
	private static int ROW_COUNT = -1;
	private static int COL_COUNT = -1;
	private Context context;
	private Drawable backImage;
	private int[][] cards;
	private List<Drawable> images;
	private Card firstCard;
	private Card seconedCard;
	private ButtonListener buttonListener;
	private int size;
	private int picked = 0;
	private static Object lock = new Object();
	JSONArray array;
	int turns;
	private TableLayout mainTable;
	private UpdateCardsHandler handler;
	String level , time;
	int score;
	TextView tv;
	int height,width;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.singlemode);
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		height = metrics.heightPixels;
		width = metrics.widthPixels;
		
		backImage = getResources().getDrawable(R.drawable.icon);
		handler = new UpdateCardsHandler();
		loadImages();
		Intent intent = getIntent();
		row = intent.getIntExtra("row", 2);
		column = intent.getIntExtra("column", 2);
		Log.i("row", "row=" + row);
		Log.i("column", "column=" + column);

		buttonListener = new ButtonListener();

		mainTable = (TableLayout) findViewById(R.id.TableLayout03);
		
		context = mainTable.getContext();
		newGame(row, column);
	
	}

	private void newGame(int c, int r) {
		ROW_COUNT = r;
		COL_COUNT = c;

		cards = new int[COL_COUNT][ROW_COUNT];

		/*
		 * mainTable.removeView(findViewById(R.id.TableRow01));
		 * mainTable.removeView(findViewById(R.id.TableRow02));
		 * 
		 * TableRow tr = ((TableRow)findViewById(R.id.TableRow03));
		 * tr.removeAllViews();
		 */
		TableRow tr = (TableRow) findViewById(R.id.TableRow03);
		mainTable = new TableLayout(context);
		tr.addView(mainTable);

		for (int y = 0; y < ROW_COUNT; y++) {
			mainTable.addView(createRow(y));
		}

		firstCard = null;
		loadCards();

		turns = 0;
		tv = (TextView) findViewById(R.id.tv1);
				tv.setText("Tries: " + turns);
				tv.setTextSize((4*width)/100);
	}
	private void HighScore(int size) {
		switch(size){
		case 12: Record("easy") ;
		break;
		case 20: Record("normal") ;
		break;
		case 30: Record("hard");
		break;
		}
		
	}
	
	private void Record(String dif) {
		if (dif.equals("easy")){
			SharedPreferences easy_SP = context.getSharedPreferences("easy", Context.MODE_WORLD_READABLE);
			if (easy_SP.getInt("easy_score",0) == 0 || turns <= easy_SP.getInt("easy_score",0) ){
				saveScore(context,turns,getTime(),"easy");
				
			}
			Log.i("TIME",getTime());
			Intent intent = new Intent(this, HighScore.class);			
			startActivity(intent);
			finish();
		}else if (dif.equals("normal")){
			SharedPreferences normal_SP = context.getSharedPreferences("normal", Context.MODE_WORLD_READABLE);
			if (normal_SP.getInt("normal_score",0) == 0 || turns <= normal_SP.getInt("normal_score",0) ){
				saveScore(context,turns,getTime(),"normal");
				
			}
			Intent intent = new Intent(this, HighScore.class);			
			startActivity(intent);
			finish();
		}else if (dif.equals("hard")){
			SharedPreferences hard_SP = context.getSharedPreferences("hard", Context.MODE_WORLD_READABLE);
			if (hard_SP.getInt("hard_score",0) == 0 || turns <= hard_SP.getInt("hard_score",0) ){
				saveScore(context,turns,getTime(),"hard");
				
			}
			Intent intent = new Intent(this, HighScore.class);			
			startActivity(intent);
			finish();
		}
		
	}
	
	private String getTime(){
		String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
		Log.i("TIME",mydate);
		return mydate;
	}
	public static void saveScore(Context context, int score,String time,String level){
	    SharedPreferences sharedPreferences = context.getSharedPreferences(level, Context.MODE_WORLD_READABLE);
	    SharedPreferences.Editor editor = sharedPreferences.edit();
	    editor.putInt(level+"_"+"score", score);
	    editor.putString(level+"_"+"time", time);
	    editor.commit();
	}
	
	private void loadImages() {
		images = new ArrayList<Drawable>();

		images.add(getResources().getDrawable(R.drawable.card1));
		images.add(getResources().getDrawable(R.drawable.card2));
		images.add(getResources().getDrawable(R.drawable.card3));
		images.add(getResources().getDrawable(R.drawable.card4));
		images.add(getResources().getDrawable(R.drawable.card5));
		images.add(getResources().getDrawable(R.drawable.card6));
		images.add(getResources().getDrawable(R.drawable.card7));
		images.add(getResources().getDrawable(R.drawable.card8));
		images.add(getResources().getDrawable(R.drawable.card9));
		images.add(getResources().getDrawable(R.drawable.card10));
		images.add(getResources().getDrawable(R.drawable.card11));
		images.add(getResources().getDrawable(R.drawable.card12));
		images.add(getResources().getDrawable(R.drawable.card13));
		images.add(getResources().getDrawable(R.drawable.card14));
		images.add(getResources().getDrawable(R.drawable.card15));
		
	}

	private void loadCards() {
		try {
			size = ROW_COUNT * COL_COUNT;

			Log.i("loadCards()", "size=" + size);

			ArrayList<Integer> list = new ArrayList<Integer>();

			for (int i = 0; i < size; i++) {
				list.add(new Integer(i));
			}

			Random r = new Random();

			for (int i = size - 1; i >= 0; i--) {
				int t = 0;

				if (i > 0) {
					t = r.nextInt(i);
				}

				t = list.remove(t).intValue();
				cards[i % COL_COUNT][i / COL_COUNT] = t % (size / 2);

				Log.i("loadCards()", "card[" + (i % COL_COUNT) + "]["
						+ (i / COL_COUNT) + "]="
						+ cards[i % COL_COUNT][i / COL_COUNT]);
			}
		} catch (Exception e) {
			Log.e("loadCards()", e + "");
		}

	}

	private TableRow createRow(int y) {
		TableRow row = new TableRow(context);
		row.setHorizontalGravity(Gravity.CENTER);

		for (int x = 0; x < COL_COUNT; x++) {
			row.addView(createImageButton(x, y));
		}
		return row;
	}

	private View createImageButton(int x, int y) {
		Button button = new Button(context);
		button.setBackgroundDrawable(backImage);
		button.setId(100 * x + y);
		button.setOnClickListener(buttonListener);
		return button;
	}

	class ButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			synchronized (lock) {
				if (firstCard != null && seconedCard != null) {
					return;
				}
				int id = v.getId();
				int x = id / 100;
				int y = id % 100;
				turnCard((Button) v, x, y);
			}

		}

		private void turnCard(Button button, int x, int y) {
			button.setBackgroundDrawable(images.get(cards[x][y]));

			if (firstCard == null) {
				firstCard = new Card(button, x, y);
			} else {

				if (firstCard.x == x && firstCard.y == y) {
					return; // the user pressed the same card
				}

				seconedCard = new Card(button, x, y);

				turns++;
				((TextView) findViewById(R.id.tv1)).setText("Tries: " + turns);

				TimerTask tt = new TimerTask() {

					@Override
					public void run() {
						try {
							synchronized (lock) {
								handler.sendEmptyMessage(0);
							}
						} catch (Exception e) {
							Log.e("E1", e.getMessage());
						}
					}
				};

				Timer t = new Timer(false);
				t.schedule(tt, 1300);
			}

		}

	}

	class UpdateCardsHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			synchronized (lock) {
				checkCards();
				if (picked == size) {
					picked = 0;
					HighScore(size);
					
				}

			}
		}

		public void checkCards() {
			if (cards[seconedCard.x][seconedCard.y] == cards[firstCard.x][firstCard.y]) {
				firstCard.button.setVisibility(View.INVISIBLE);
				seconedCard.button.setVisibility(View.INVISIBLE);
				picked += 2;
			} else {
				seconedCard.button.setBackgroundDrawable(backImage);
				firstCard.button.setBackgroundDrawable(backImage);
			}

			firstCard = null;
			seconedCard = null;
		}

	
	}

}
